package java6681.lesson03;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.Scanner;

/**
 * @author Junichiro
 * @description 计算某月最后一天
 * @date 2021-03-21 21:38
 **/

public class LastDay6681 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("计算某月的最后一天");
        System.out.print("请按yyyy-mm的格式输出：");
        /*从键盘输入年月*/
        String str = sc.nextLine();
        System.out.println("本月最后一天是" + getLastDay6681(str) + "日");
    }

    /**
     * 功能：计算某月最后一天
     *
     * @param date String类型，输入日期
     * @return endDate String类型，按指定格式输出某月的最后一天
     */
    public static String getLastDay6681(String date) {
        /*日期的规则*/
        String strPattern = "yyyy-M-dd";
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME.ofPattern(strPattern);
        /*去掉空格*/
        date = date.trim().replaceAll(" ", "");
        /*存最后一天*/
        String endDate;
        /*判断条件是否满足*/
        try {
            LocalDate localDate = LocalDate.parse(date + "-01", formatter);
            TemporalAdjuster day = TemporalAdjusters.lastDayOfMonth();
            localDate = localDate.with(day);
            int end = localDate.getDayOfMonth();
            endDate = "" + end;
        } catch (Exception e) {
            return null;
        }
        return endDate;
    }
}

